package com.zhaozhaonews.search.service.impl;


import com.zhaozhaonews.model.common.dto.ResponseResult;
import com.zhaozhaonews.model.common.enums.AppHttpCodeEnum;
import com.zhaozhaonews.model.serach.dto.HistorySearchDto;
import com.zhaozhaonews.model.serach.entity.ApUserSearch;
import com.zhaozhaonews.model.user.entity.ApUser;
import com.zhaozhaonews.search.service.ApUserSearchService;
import com.zhaozhaonews.util.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author WanJl
 * @version 1.0
 * @title ApUserSearchServiceImpl
 * @description
 * @create 2025/2/22
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜素历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void save(String keyword, Integer userId) {
        //1、查询当前用户的搜索搜索词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2、判断是否存在，存在就更新时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3、不存在就判断当前的历史记录是否超过10，超过了就替换最后一个
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);
        //如果查询到的搜索词列表为空，或者长度小于10
        if (apUserSearchList == null || apUserSearchList.size() < 10) {
            //正常添加搜索词记录
            mongoTemplate.save(apUserSearch);
        } else {
            //找到最后一个搜索词
            ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            //移除最后一个搜索词
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())), apUserSearch);
        }

    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        //根据用户查询数据
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(Query.query(
                        Criteria.where("userId")
                                .is(user.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);

        return ResponseResult.okResult(apUserSearchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //验证参数
        if (dto.getId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        //获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        mongoTemplate.remove(Query.query(
                Criteria.where("userId")
                        .is(user.getId())
                        .and("id")
                        .is(dto.getId())), ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
